import { createStore } from 'vuex'
import request from '@/utils/request'

const AUTH_STORAGE_KEY = 'iot_frontend_auth'

export default createStore({
  state: {
    token: null,
    user: null
  },
  getters: {
    isAuthenticated(state) {
      return Boolean(state.token)
    },
    username(state) {
      return state.user?.username || ''
    },
    role(state) {
      return state.user?.role ?? null
    },
    isAdmin(state) {
      return Number(state.user?.role) === 2
    }
  },
  mutations: {
    setAuth(state, payload) {
      state.token = payload?.token || null
      state.user = payload?.user || null
    },
    clearAuth(state) {
      state.token = null
      state.user = null
    }
  },
  actions: {
    initializeAuth({ commit }) {
      try {
        const stored = localStorage.getItem(AUTH_STORAGE_KEY)
        if (stored) {
          const parsed = JSON.parse(stored)
          commit('setAuth', parsed)
        }
      } catch (e) {
        console.error('Failed to initialize auth from storage', e)
      }
    },
    async login({ commit }, { username, password }) {
      if (!username || !password) {
        throw new Error('请输入用户名和密码')
      }
      // 调用后端登录接口（后端使用 @RequestParam，需以表单方式提交）
      const params = new URLSearchParams()
      params.append('username', username)
      params.append('password', password)
      const res = await request.post('/user/login', params, {
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
      })

      const data = res?.data
      const headers = res?.headers || {}

      // 兼容常见返回格式：
      // - { code: 200, data: { token, user }, msg }
      // - { state: 200, data: { token, user }, message }
      // - { token, user }
      // - { access_token, user }
      // 以及从响应头获取：authorization/token/x-token
      let token
      let user
      const successCode = (val) => val === 200 || val === 0 || val === '200'

      if (data && typeof data === 'object') {
        if (Object.prototype.hasOwnProperty.call(data, 'code')) {
          if (!successCode(data.code)) {
            throw new Error(data.msg || data.message || '登录失败')
          }
          token = data.data?.token ?? data.data?.accessToken ?? data.token ?? data.access_token
          user = data.data?.user ?? data.user ?? { username }
        } else if (Object.prototype.hasOwnProperty.call(data, 'state')) {
          if (!successCode(data.state)) {
            throw new Error(data.message || data.msg || '登录失败')
          }
          token = data.data?.token ?? data.token ?? data.data?.accessToken ?? data.access_token
          user = data.data?.user ?? data.user ?? { username }
        } else {
          token = data.token ?? data.access_token ?? data.data?.token ?? data.data?.accessToken
          user = data.user ?? data.data?.user ?? { username }
        }
      }

      // 尝试从响应头解析
      if (!token && headers) {
        const headerAuth = headers['authorization'] || headers['Authorization']
        const headerToken = headers['token'] || headers['Token'] || headers['x-token'] || headers['X-Token']
        if (headerAuth && typeof headerAuth === 'string') {
          token = headerAuth.startsWith('Bearer ') ? headerAuth.slice(7) : headerAuth
        } else if (headerToken && typeof headerToken === 'string') {
          token = headerToken
        }
      }

      if (!token) {
        throw new Error('登录失败：未获取到令牌')
      }
      const auth = { token, user }
      commit('setAuth', auth)
      localStorage.setItem(AUTH_STORAGE_KEY, JSON.stringify(auth))
      return true
    },
    logout({ commit }) {
      commit('clearAuth')
      localStorage.removeItem(AUTH_STORAGE_KEY)
    },
    async fetchProfile({ state, commit }) {
      // 使用已登录 token 调用后端个人信息接口
      const res = await request.post('/user/profile')
      const data = res?.data
      // 兼容常见返回：{ state: 200, data: {...} } 或 { code: 200, data: {...} } 或直接返回用户对象
      const successCode = (val) => val === 200 || val === 0 || val === '200'
      let user
      if (data && typeof data === 'object') {
        if (Object.prototype.hasOwnProperty.call(data, 'state')) {
          if (!successCode(data.state)) throw new Error(data.message || '获取个人信息失败')
          user = data.data
        } else if (Object.prototype.hasOwnProperty.call(data, 'code')) {
          if (!successCode(data.code)) throw new Error(data.msg || '获取个人信息失败')
          user = data.data
        } else {
          user = data
        }
      }
      if (!user) throw new Error('获取个人信息失败：返回为空')
      // 保留现有 token，更新 user
      commit('setAuth', { token: state.token, user })
      localStorage.setItem(AUTH_STORAGE_KEY, JSON.stringify({ token: state.token, user }))
      return user
    }
  },
  modules: {
  }
})
